$(function () {
    //日期插件
	$('#reservation1').daterangepicker({
		locale : {  
	    	format: 'YYYY-MM-DD',
	    	separator:' 到 ',
	        applyLabel : '确定',  
	        cancelLabel : '取消',  
	        customRangeLabel : '自定义',  
	        daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],  
	        monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月',  
	                '七月', '八月', '九月', '十月', '十一月', '十二月' ],  
	        firstDay : 1 , 
	    },  
	    ranges: {
			'今天': [moment().startOf('day'), moment()],
			'昨天': [moment().subtract(1,'days').startOf('day'), moment().subtract(1,'days').endOf('day')],
			'本周': [moment().startOf("week").add(1,'days'),moment().endOf("week").add(1,'days')],
			'上周': [moment().subtract(1,'weeks').startOf("week").add(1,'days'),moment().subtract(1,'weeks').endOf("week").endOf("week").add(1,'days')],
			'本月': [moment().startOf("month"),moment().endOf("month")],
			'上个月': [moment().subtract(1,"month").startOf("month"),moment().subtract(1,"month").endOf("month")],
			'最近7天': [moment().subtract(6,'days'), moment()],
			'最近30天': [moment().subtract(29,'days'), moment()]
	     },
	     applyClass:'btn-primary',
	     alwaysShowCalendars: true,
	     autoclose:true
	});
    //信息提示　
    $(".distribute").on({
        mouseover:function(){
            $(this).attr('data-content', $('.distributionInfo').html());
        },
        click: function () {
            $(this).popover({html: true});
        }
    });

    //按钮切换
    $(".tab_content_11 li").hover(function () {
        $(this).find("div").css({"display": "block", "transform": "rotate3d(0deg,30deg)"});
    }, function () {
        $(this).find("div").css({"display": "none"})
    });
    init();
    
    $('#init').on('click', '.edit', function(){
    	var record = $(this).data('record');
    	$('#departmentName1').val(record.departmentName1);
    	$('#phoneBelongView').val(record.phoneBelong);
    	$('#brandNameView').val(record.brandName);
    	$('#studentAttrName2').val(record.studentAttrName2);
    	$('#studentAttrName1').val(record.studentAttrName1);
    	$('#keywordView').val(record.keyword);
    	$('#pageUrlView').val(record.pageUrl);
    	$('#studentNameView').val(record.studentName);
    	$('#studentPhoneView').val(record.studentPhone);
    	$('#studentSexView').val(record.studentSex?"女":"男");
    	$('#wechatView').val(record.weChat);
    	$('#ageView').val(record.age);
    	$('#tengXunView').val(record.tengXun);
    	$('#projectNameView').val(record.projectName);
    	$('#projectLevelNameView').val(record.projectLevelName);
    	$('#studentAttrName3').val(record.studentAttrName3);
    	$('#notesView').val(record.notes);
    	$('#conversationView').val(record.conversation);
    	
    	editor2.html(record.conversation);
    	
    	$('#viewInfo').modal('show');
    	
    })
})
$(document).on('change', 'input:checkbox.master', function(){
		if($(this).prop('checked')){
			$('input:checkbox.slaver').prop('checked', 'checked');
		}else{
			$('input:checkbox.slaver').prop('checked', '');
		}
})
/**
 * 初始化
 * @returns
 */
function init (){
	var init = $('#init').dataTable({
		"bAutoWidth" : false,
		"bFilter" : false,
		"bPaginate":true,
		"bSort": false, //是否支持排序功能
		"bLengthChange": true, 
		"oLanguage" : {
			"sLengthMenu" : "每页显示 _MENU_ 条记录",
			"sZeroRecords" : "抱歉， 没有找到",
			"sInfo" : "从 _START_ 到 _END_ / 共 _TOTAL_ 条数据",
			"sInfoEmpty" : "",
			"sInfoFiltered" : "",
			"oPaginate" : {
				"sFirst" : "首页",
				"sPrevious" : "前一页",
				"sNext" : "后一页",
				"sLast" : "尾页"
			},
			"sProcessing" : ""
		},
		"sAjaxSource" : ctx+'/consultInfoManage/loadD',
		"bDestroy" : true,
		"bRetrieve" : false,
		"bServerSide" : true,
		"fnServerData" : retrieveData,
		"aoColumns" : [
			{"mDataProp" : "infoManageId",'sClass': "text-center","mRender": function ( data, type, full ) {
				if(full["status"]=="1"||full["status"]=="2"){
					return "<label> <input id="+data+" type='checkbox' class='slaver'> <span class='text'></span> </label>";
				}else{
					return "<span class='glyphicon glyphicon-ban-circle'></span>";
				}
              }},
            {"mDataProp" : "departmentName1","bSortable": false,'sClass': "text-center"},
			{"mDataProp" : "projectName","bSortable": false,'sClass': "text-center"},
			{"mDataProp" : "projectLevelName","bSortable": false,'sClass': "text-center"},
			{"mDataProp" : "studentName","bSortable": false,'sClass': "text-center"},
              {"mDataProp" : "departmentName2","bSortable": false,'sClass': "text-center"},
              {"mDataProp" : "counselor","bSortable": false,'sClass': "text-center"},
              {"mDataProp" : "","bSortable": false,'sClass': "text-center","mRender": function ( data, type, full ) {
            	  var u = "<a data-record='"+JSON.stringify(full)+"' class='btn btn-warning btn-xs edit' data-backdrop='static'><i class='fa fa-folder-open-o'></i> 查看</a>";
            	  return u;
              }}],
			"aoColumnDefs" : [{
   	            sDefaultContent: '',
   	            aTargets: [ '_all' ]
	   	      }]
		});
}

/**
 * 回调函数
 * @param sSource
 * @param aoData
 * @param fnCallback
 * @returns
 */
function retrieveData(sSource, aoData, fnCallback, oSettings ){
	/**
	 * 参数添加
	 */
	aoData.push( { "name": "pageNum", "value": (Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength )+1) });
	aoData.push( { "name": "pageSize", "value": oSettings._iDisplayLength });	
	aoData.push( { "name": "beginTime", "value": $("#reservation1").val().split("到")[0] } );
	aoData.push( { "name": "endTime", "value": $("#reservation1").val().split("到")[1] } );
	aoData.push( { "name": "departmentId2", "value": infoDisDep } );
	aoData.push( { "name": "searchVal", "value": $("#searchVal").val()} );
	$.ajax({
		"type" : "Post",
		"url" : sSource,
		"dataType" : "json",
		"data" : aoData,
		"success" : function(resp) {
			fnCallback(resp.returnObject);
		}
	});
	//每页显示记录数
	$('.dataTables_info').parent().append($('.dataTables_length'));
}
function toChooseAr(){
	var idAr = "";
	$('.slaver').each(function(){
		if(this.checked){
			idAr = idAr + this.id + ",";
		}
	})
	idAr = idAr.substring(0,idAr.length-1);
	var counselor =  $('#status').find("option:selected").text();
	var counselorId = $('#status').val();
	if(counselorId == '0'){
		toastr.error('当前咨询师无效');
		return;
	}
	$.ajax({
		"type" : "Post",
		"url" : ctx+"/consultDistributeCenter/toChooseAr",
		"dataType" : "json",
		"data" : {
			ar : idAr,
			counselor:counselor,
			counselorId:counselorId,
			status:2
		},
		"success" : function(data) {
			if(data=="success"){
				toastr.success('分配完成');
				init();
			}
		}
	});	
}


//回车搜索
function search(){
	if(event.keyCode==13){
		init();
	}
}